import { useState, useEffect } from 'react';
import { Form, Input, Select, Space, Table, Tag, Button, Modal } from 'antd';
import axios from 'axios';
import { SearchOutlined, UndoOutlined } from '@ant-design/icons';

const OperationLog = () => {
  const [searchForm] = Form.useForm();
  const [data, setData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedLog, setSelectedLog] = useState(null);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [deleteIds, setDeleteIds] = useState([]); // 批量删除的ID集合
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  useEffect(() => {
    // 从后端API获取数据
    axios.get('http://localhost:8080/api/operationlogs')
      .then((response) => {
        setData(response.data);
        setFilteredData(response.data);
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
      });
  }, []);

  const onFinish = (values) => {
    // 根据表单值过滤数据
    const filteredLogs = data.filter((log) => {
      const matchesOperation = !values.operation || log.operation.includes(values.operation);
      const matchesStatus = !values.status || log.status.includes(values.status);

      return matchesOperation && matchesStatus;
    });

    setFilteredData(filteredLogs);
  };

  const resetForm = () => {
    searchForm.resetFields();
    setFilteredData(data);
  };

  const showDetails = (log) => {
    setSelectedLog(log);
    setIsModalVisible(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const showDeleteConfirm = (ids) => {
    setDeleteIds(ids);
    setDeleteModalVisible(true);
  };

  const handleDeleteConfirm = () => {
    Promise.all(deleteIds.map(id => axios.delete(`http://localhost:8080/api/operationlogs/${id}`)))
      .then(() => {
        // 更新数据列表
        setData(data.filter(item => !deleteIds.includes(item.id)));
        setFilteredData(filteredData.filter(item => !deleteIds.includes(item.id)));
        setSelectedRowKeys([]);
        setDeleteModalVisible(false);
      })
      .catch((error) => {
        console.error('Error deleting logs:', error);
      });
  };

  const handleDeleteCancel = () => {
    setDeleteModalVisible(false);
  };

  const onSelectChange = (selectedRowKeys) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const rowSelection = {
    onChange: onSelectChange,
    selectedRowKeys,
  };

  const columns = [
    {
      title: '日志编号',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '用户操作',
      dataIndex: 'operation',
      key: 'operation',
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
    },
    {
      title: '执行时间(ms)',
      dataIndex: 'elapsedTime',
      key: 'elapsedTime',
    },
    {
      title: '操作时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      render: (status) => {
        if (!Array.isArray(status)) {
          status = [status];
        }
        return (
          <>
            {status.map((tag) => {
              let color = tag === '成功' ? 'green' : tag === '失败' ? 'red' : 'geekblue';
              return (
                <Tag color={color} key={tag}>
                  {tag.toUpperCase()}
                </Tag>
              );
            })}
          </>
        );
      },
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => showDetails(record)}>详情</a>
          <a onClick={() => showDeleteConfirm([record.id])} style={{ color: '#ed5565' }}>删除</a>
        </Space>
      ),
    },
  ];

  const batchDeleteButton = (
    <Button
      type="danger"
      onClick={() => showDeleteConfirm(selectedRowKeys)}
      disabled={!selectedRowKeys.length}
      style={{
        marginTop: 16, // 上边距
        marginBottom: 16, // 下边距
        width: 100,
        backgroundColor: '#ed5565',
        color: '#fff'
      }}
    >
      批量删除
    </Button>
  );

  return (
    <div>
      <Form form={searchForm} layout="inline" onFinish={onFinish}>
        <Form.Item name="operation" label="用户操作">
          <Input placeholder="请输入用户操作" />
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select placeholder="请选择状态">
            <Select.Option value="成功">成功</Select.Option>
            <Select.Option value="失败">失败</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button
              type="primary"
              htmlType="submit"
              icon={<SearchOutlined />}
              style={{ marginLeft: 8, width: 70, backgroundColor: '#1ab394', color: '#fff' }}
            >
              搜索
            </Button>
            <Button
              onClick={resetForm}
              icon={<UndoOutlined />}
              style={{ marginLeft: 8, width: 70, backgroundColor: '#3c79d9', color: '#fff' }}
            >
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>

      {batchDeleteButton}

      <Table 
        rowSelection={rowSelection}
        columns={columns} 
        dataSource={filteredData} 
        rowKey="id"
      />

      <Modal
        title="操作日志详情"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleOk} // 确保点击右上角的关闭按钮也能触发关闭
        footer={null} // 移除底部的所有按钮
      >
        {selectedLog && (
          <div>
            <p><strong>日志编号:</strong> {selectedLog.id}</p>
            <p><strong>用户名:</strong> {selectedLog.username}</p>
            <p><strong>用户操作:</strong> {selectedLog.operation}</p>
            <p><strong>方法:</strong> {selectedLog.method}</p>
            <p><strong>参数:</strong> {selectedLog.params}</p>
            <p><strong>结果:</strong> {selectedLog.result}</p>
            <p><strong>执行时间(ms):</strong> {selectedLog.elapsedTime}</p>
            <p><strong>操作时间:</strong> {selectedLog.createTime}</p>
            <p><strong>IP地址:</strong> {selectedLog.ipAddress}</p>
            <p><strong>状态:</strong> {selectedLog.status}</p>
          </div>
        )}
      </Modal>
      <Modal
        title="确认删除"
        visible={deleteModalVisible}
        onCancel={handleDeleteCancel}
        footer={null} // 移除默认的底部按钮
      >
        <p>你是否确定要删除这些记录?</p>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
          <Button onClick={handleDeleteCancel} style={{ marginLeft: 8, width: 100 }}>取消</Button>
          <Button type="default" onClick={handleDeleteConfirm} style={{ marginLeft: 8, width: 100, backgroundColor: '#ed5565', color: '#fff' }}>确定</Button>
        </div>
      </Modal>
    </div>
  );
};

export default OperationLog;